package com.shuai.user.service.impl;

import  cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shuai.common.constant.AuthenticationConstant;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.constant.UserConstant;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.utils.MyJWTUtil;
import com.shuai.common.utils.PasswordUtil;
import com.shuai.user.domain.entity.User;
import com.shuai.user.domain.request.UserRegisterRequest;
import com.shuai.user.domain.request.UserUpdateRequest;
import com.shuai.user.mapper.UserMapper;
import com.shuai.user.service.EmailService;
import com.shuai.user.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.UUID;

/**
 * @author bxs
 * @description 针对表【user(用户表)】的数据库操作Service实现
 * @createDate 2024-07-04 13:19:29
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private EmailService emailService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User register(UserRegisterRequest registerRequest) {
        if (!emailService.validateEmailCode(registerRequest.getEmail(), registerRequest.getEmailCode())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱验证码错误");
        }
        emailService.removeEmailCode(registerRequest.getEmail());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserEmail, registerRequest.getEmail())
                .or()
                .eq(User::getUsername, registerRequest.getUsername())
                .or()
                .eq(User::getMobile, registerRequest.getMobile());
        List<User> userList = this.list(queryWrapper);
        if (!userList.isEmpty()) {
            for (User user : userList) {
                if (CharSequenceUtil.isNotBlank(user.getUserEmail()) && user.getUserEmail().equals(registerRequest.getEmail())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "邮箱已存在");
                } else if (CharSequenceUtil.isNotBlank(user.getUsername()) && user.getUsername().equals(registerRequest.getUsername())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户名已存在");
                } else if (CharSequenceUtil.isNotBlank(user.getMobile()) && user.getMobile().equals(registerRequest.getMobile())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "手机号已存在");
                }
            }
        }
        User user = new User();
        BeanUtils.copyProperties(registerRequest, user);
        user.setUserPassword(PasswordUtil.encryptPwd(registerRequest.getUserPassword()));
        user.setApiKey(UUID.randomUUID().toString().replaceAll("-", ""));
        user.setApiSecret(UUID.randomUUID().toString().replaceAll("-", ""));
        this.save(user);
        return user;
    }

    @Override
    public User getUserInfo(String authentication) {
        Object payLoadItem = MyJWTUtil.getPayLoadItem(authentication, AuthenticationConstant.PAYLOAD_USERID);
        if (payLoadItem == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户信息已过期,请重新登录");
        }
        String userId = payLoadItem.toString();
        String userJson = stringRedisTemplate.opsForValue().get(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId);
        if (CharSequenceUtil.isBlank(userJson)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户信息已过期,请重新登录");
        }
        return JSONUtil.toBean(userJson, User.class);
    }

    @Override
    public User updateUserInfo(String authentication, UserUpdateRequest userUpdateRequest) {
        Object payLoadItem = MyJWTUtil.getPayLoadItem(authentication, AuthenticationConstant.PAYLOAD_USERID);
        String userId = payLoadItem.toString();
        if (StringUtils.isBlank(userId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户信息已过期,请重新登录");
        }
        User user = this.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        User build = User.builder()
                .id(Long.parseLong(userId))
                .username(userUpdateRequest.getUsername())
                .userAvatar(userUpdateRequest.getHeader())
                .build();
        this.updateById(build);
        if (StringUtils.isNotBlank(userUpdateRequest.getUsername())) {
            user.setUsername(userUpdateRequest.getUsername());
        }
        if (StringUtils.isNotBlank(userUpdateRequest.getHeader())) {
            user.setUserAvatar(userUpdateRequest.getHeader());
        }
        stringRedisTemplate.opsForValue().set(UserConstant.USER_ATTRIBUTE_REDIS_KEY + userId, JSONUtil.toJsonStr(user));
        return build;
    }

    @Override
    public void outLogin(String authentication, HttpServletResponse response) {
        Object payLoadItem = MyJWTUtil.getPayLoadItem(authentication, AuthenticationConstant.PAYLOAD_USERID);
        if (payLoadItem == null) {
            return;
        }
        stringRedisTemplate.delete(UserConstant.USER_ATTRIBUTE_REDIS_KEY + payLoadItem);
        response.setHeader(AuthenticationConstant.AUTHENTICATION_HEADER, "");
    }

}




